package ar.pmt.gwt.client.core;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import ar.pmt.vista.beans.RecursoBean;
import ar.pmt.vista.beans.VistaBean;

import com.gwtext.client.core.Connection;
import com.gwtext.client.core.UrlParam;
import com.gwtext.client.widgets.form.Form;


public final class UtilGwt {
	
	public static void submitForm(final Form form, String call ,UrlParam[] urlParams, String msgWait, boolean clientValidation){		
		UrlParam[] urlParamAux = new UrlParam[1];
		if(urlParams!=null && urlParams.length>0){
			urlParamAux = new UrlParam[urlParams.length+1];
			for (int i = 0; i < urlParamAux.length-1; i++) {
				urlParamAux[i] = urlParams[i];
			}
		}
		urlParamAux[urlParamAux.length-1] = new UrlParam(ConstantesGwt.OPERATIONFORM_TYPE_CLAVE, ConstantesGwt.OPERATIONFORM_TYPE_SUBMIT);
		if(form!=null){
			form.submit(call, urlParamAux, Connection.POST, msgWait, clientValidation);
		}
	}
	
	public static void loadForm(final Form form, String call ,UrlParam[] urlParams, String msgWait){	
		UrlParam[] urlParamAux = new UrlParam[1];
		if(urlParams!=null || urlParams.length>0){
			urlParamAux = new UrlParam[urlParams.length+1];
			for (int i = 0; i < urlParamAux.length-1; i++) {
				urlParamAux[i] = urlParams[i];
			}
		}
		urlParamAux[urlParamAux.length-1] = new UrlParam(ConstantesGwt.OPERATIONFORM_TYPE_CLAVE, ConstantesGwt.OPERATIONFORM_TYPE_LOAD);
		if(form!=null){
			form.load(call, urlParamAux, Connection.POST, msgWait);
		}
	}
	
	
	
	public static UrlParam[] methodRequestToUrlParam(MethodRequest methodRequest){
		int size = methodRequest.getClasesArg().size()+methodRequest.getAtributosExtras().size()+3;
		UrlParam[] urlParam = new UrlParam[size];
		urlParam[0] = new UrlParam("_clase",methodRequest.getClase() );
		urlParam[1] = new UrlParam("_metodo",methodRequest.getMetodo() ); 
		urlParam[2] = new UrlParam("_template",methodRequest.getTemplateOut()); 
		int i=3;
		Iterator<Class<? extends VistaBean >> itClase = methodRequest.getClasesArg().iterator();
		while (itClase.hasNext()) {
			Class<? extends VistaBean > claseArg = (Class<? extends VistaBean >) itClase.next();
			urlParam[i]= new UrlParam("_clasesArg",claseArg.getName() ); 
			i++;
		}
		
		Iterator<Entry<String, String>> itAtributosExtras = methodRequest.getAtributosExtras().entrySet().iterator();
		while (itAtributosExtras.hasNext()) {
		        Map.Entry<String, String> pairs = (Map.Entry<String, String>)itAtributosExtras.next();
		        urlParam[i]= new UrlParam(pairs.getKey(),pairs.getValue()); 
		        i++;
		}
		return urlParam;
		
	}

}
